package com.asus.api;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

public class CreRegApi extends ApiBase
{

	HttpPost ad;
	
	public CreRegApi(HashMap<String, String> pHashMap)
	{
		super(
				"https://vip.asus.com/webservice/app_cusinfo.asmx/CreRegProfile?",
				pHashMap);
		
		ad = new HttpPost("https://vip.asus.com/webservice/app_cusinfo.asmx/CreRegProfile?");
		
		
		BasicHttpParams _Param = new BasicHttpParams();
		
		for (Entry<String, String> item: mHashMap.entrySet())
		{
			_Param.setParameter(item.getKey(), item.getValue());
		}
		
		ad.setParams(_Param);
	}
	
	private HashMap<String, String> mHashMap =  new HashMap<String, String>();

	protected Boolean Run2()
	{
		try
		{
			HttpResponse _HttpResponse = mHttpClient.execute(ad);
			InputStream _InputStream = _HttpResponse.getEntity().getContent();
			
			DocumentBuilderFactory _Factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder _Builder = _Factory.newDocumentBuilder();
			Document _Document = _Builder.parse(_InputStream);
			mRootElement = _Document.getDocumentElement();
			
			return true;
			
		}
		catch (Exception e) {
			Log.i("Macalog", e.toString());
			return false;
		}
	}
	
	public Boolean Start()
	{
		if (Run2())
		{
			try
			{

				NodeList _List = mRootElement.getElementsByTagName("ASUS");

				for (int i = 0; i < _List.getLength(); i++)
				{
					mHashMap = new HashMap<String, String>();
					for (int j = 0; j < _List.item(i).getChildNodes()
							.getLength(); j++)
					{
						Node _Node = _List.item(i).getChildNodes().item(j);
						if (_List.item(i).getChildNodes().item(j).getNodeName() == "#text")
						{
						} else
						{
							mHashMap.put(_Node.getNodeName(),
									_Node.getTextContent());
						}
					}
				}

				return true;

			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

	public HashMap<String, String> getHashMap()
	{
		return mHashMap;
	}

}
